package org.rslai.tcedit.web.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.validator.InvalidStateException;
import org.hibernate.validator.InvalidValue;
import org.rslai.tcedit.domain.Role;
import org.rslai.tcedit.exception.ApplicationException;
import org.rslai.tcedit.security.LoadRoleResource;
import org.rslai.tcedit.util.HttpUtil;
import org.rslai.tcedit.util.XmlUtil;
import org.rslai.tcedit.web.core.AbstractMvcController;
import org.springframework.core.io.Resource;
import org.dom4j.Document;
import org.dom4j.Element;

/**
 * 角色管理
 * 
 * @author rslai
 * 
 * @spring.bean name="/admin/role.jspx"
 */
public class RoleController extends AbstractMvcController {
	private LoadRoleResource loadRoleResource;
	private Resource resourcePermission;

	/**
	 * 设置装载角色对应资源
	 * 
	 * @spring.property ref="loadRoleResource"
	 */
	public void setLoadRoleResource(LoadRoleResource loadRoleResource) {
		this.loadRoleResource = loadRoleResource;
	}

	/**
	 * 设置权限配置信息文件
	 * 
	 * @spring.property value="/WEB-INF/permission.xml"
	 */
	public void setResourcePermission(Resource resourcePermission) {
		this.resourcePermission = resourcePermission;
	}

	@Override
	public Map<String, Object> getModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String method = request.getMethod();
		Map<String, Object> map = new HashMap<String, Object>();
		Role role = null;

		String action = HttpUtil.getString(request, "action", "").toLowerCase();
		String roleID = HttpUtil.getString(request, "id", "").toLowerCase();

		try {
			if (action.equals("delete")) { // 删除
				role = (Role) roleService.query(Role.class, roleID);
				roleService.delete(role);
				this.loadRoleResource.refreshRoleResource(); // 刷新角色可以操作资源的对应信息
				response.sendRedirect("/admin/roleList.jspx");
				role = null;
			}else if (method.equals("GET")) {
				if  (roleID.isEmpty()) { // 新增（返回空对象） 
					role = new Role();
					role.setBonding(true);
				} else { // 查询
					role = (Role) roleService.query(Role.class, roleID);
				}
			}else if(method.equals("POST")) {
				if (action.equals("create")) { // 新增
					role = (Role) HttpUtil.createFormBean(request, Role.class);
					roleService.create(role);
					this.loadRoleResource.refreshRoleResource(); // 刷新角色可以操作资源的对应信息
					response.sendRedirect("/admin/roleList.jspx");
				} else if (action.equals("update")) { // 修改
					Role formRole = (Role) HttpUtil.createFormBean(request, Role.class);
					role = (Role) roleService.query(Role.class, roleID);
					role.setName(formRole.getName());
					role.setDescribing(formRole.getDescribing());
					role.setBonding(formRole.getBonding());
					role.setUrlPermissionStr(HttpUtil.getString(request, "urlPermissionStr", ""));
					role.setMethodPermissionStr(HttpUtil.getString(request, "methodPermissionStr", ""));
					roleService.update(role);
					this.loadRoleResource.refreshRoleResource(); // 刷新角色可以操作资源的对应信息
					response.sendRedirect("/admin/roleList.jspx");
				}
			}
		} catch(Exception e) {
			map.put("error", convertException(e));
		}

		Document doc = new XmlUtil().loadFromXML(resourcePermission);
		Element root = doc.getRootElement();
		List permissions = root.selectNodes("/root/module");

		map.put("action", action);
		map.put("permissions", permissions);
		map.put("role", role);

		return map;
	}

	@Override
	public String getView(HttpServletRequest request, HttpServletResponse response) {
		return "/admin/role.htm";
	}

	private String convertException(Exception e) throws Exception {
		if (e instanceof ApplicationException) {
			return e.getMessage();
		} else if (e instanceof InvalidStateException) {
			StringBuffer sb = new StringBuffer(128);
			InvalidValue[] ivs = ((InvalidStateException) e).getInvalidValues();
			for (InvalidValue iv : ivs)
				sb.append(iv.getMessage()).append("<br/>");
			return sb.toString();
		}
		throw e;
	}

}
